package me.stone.stanimeclient.page.search

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.paging.LoadState
import com.didi.drouter.annotation.Router
import com.didi.drouter.api.DRouter
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.stone.stanimeclient.Constants
import me.stone.stanimeclient.base.AbsViewBindingActivity
import me.stone.stanimeclient.core.common.extensions.launchAndRepeatWithLifecycle
import me.stone.stanimeclient.core.ui.adapters.FanIntroListGridAdapter
import me.stone.stanimeclient.core.ui.adapters.listener.OnItemClickListener
import me.stone.stanimeclient.databinding.ActivitySearchBinding

@AndroidEntryPoint
@Router(path = Constants.DROUTE_PATH_FAN_SEARCH)
class SearchActivity : AbsViewBindingActivity<ActivitySearchBinding>() {

    private val viewModel: SearchViewModel by viewModels()

    private val queryHint by lazy {
        intent.getStringExtra(Constants.DROUTE_EXTRA_KEY_CONTENT) ?: ""
    }

    private val suggestionAdapter by lazy {
        SuggestionTextAdapter(
            doQueryEvent = viewModel,
            doDeleteSuggestionEvent = viewModel,
            doClearHistoryEvent = viewModel
        )
    }

    private val resultDataAdapter by lazy {
        FanIntroListGridAdapter().apply {
            onItemClickListener = OnItemClickListener {
                DRouter.build(Constants.DROUTE_PATH_FAN_INFO)
                    .putExtra(Constants.DROUTE_EXTRA_KEY_ID, it.id)
                    .start(this@SearchActivity)
            }
        }
    }

    private var reloading: Boolean = false

    override fun buildViewBinding(): ActivitySearchBinding {
        viewModel.queryHint = queryHint
        return ActivitySearchBinding.inflate(layoutInflater).apply {
            viewModel = this@SearchActivity.viewModel
            queryHint = this@SearchActivity.queryHint
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.resultData.adapter = resultDataAdapter
        binding.suggestions.adapter = suggestionAdapter.withFooterAdapter()
        binding.refreshing.setOnRefreshListener {
            if (viewModel.queryContent.value.isNotBlank()) {
                resultDataAdapter.refresh()
            } else {
                binding.refreshing.isRefreshing = false
            }
        }
        binding.toolbar.setNavigationOnClickListener {
            // 关闭存在的虚拟键盘
            if (ViewCompat.getRootWindowInsets(window.decorView)
                    ?.getInsets(WindowInsetsCompat.Type.ime())?.bottom != 0) {
                hideKeyboard()
                return@setNavigationOnClickListener
            }

            // 关闭存在的推荐词列表
            if (hideSuggestionList()) {
                return@setNavigationOnClickListener
            }

            // 关闭搜索界面
            finish()
        }
        binding.inputQuery.requestFocus()



        launchAndRepeatWithLifecycle {

            launch {
                viewModel.resultInfo.collectLatest {
                    binding.resultInfo.text = it
                }
            }

            launch {
                viewModel.queryContent.collectLatest {
                    // 关闭推荐词列表和输入法
                    hideKeyboard()
                    hideSuggestionList()
                    // 判断是否需要设置搜索框内容
                    if (binding.inputQuery.text?.toString() != it) {
                        // 设置搜索框内容
                        viewModel.lockEditorChangedListener = true
                        binding.inputQuery.setText(it)
                        binding.inputQuery.setSelection(it.length.coerceAtMost(8))
                        viewModel.lockEditorChangedListener = false
                    }
                }
            }

            launch {
                viewModel.resultData.collectLatest {
                    hideSuggestionList()
                    resultDataAdapter.submitData(it)
                }
            }

            launch {
                resultDataAdapter.loadStateFlow.collectLatest {
                    when (it.refresh) {
                        is LoadState.Loading -> {
                            reloading = true
                        }
                        is LoadState.Error -> {
                            binding.refreshing.isRefreshing = false
                        }
                        is LoadState.NotLoading -> {
                            if (reloading && binding.refreshing.isRefreshing) {
                                binding.refreshing.isRefreshing = false
                            }
                        }
                    }
                }
            }

            launch {
                viewModel.closeSuggestionSign.collectLatest {
                    hideSuggestionList()
                }
            }

            launch {
                viewModel.suggestions.collectLatest {
                    showSuggestionList()
                    suggestionAdapter.submitData(it)
                }
            }

            launch {
                viewModel.inputContent.collectLatest {
                    suggestionAdapter.query = it
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        hideKeyboard()
    }

    private fun showSuggestionList(): Boolean {
        return (binding.suggestions.visibility == View.GONE).also {
            if (it) binding.suggestions.visibility = View.VISIBLE
        }
    }

    private fun hideSuggestionList(): Boolean {
        return (binding.suggestions.visibility == View.VISIBLE).also {
            if (it) binding.suggestions.visibility = View.GONE
        }
    }

    private fun hideKeyboard() {
        WindowCompat.getInsetsController(window, binding.inputQuery)
            .hide(WindowInsetsCompat.Type.ime())
        binding.inputQuery.clearFocus()
    }

}